package com.lkd.job;

import com.lkd.common.VMSystem;
import com.lkd.entity.UserEntity;
import com.lkd.service.UserService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Component
@Slf4j
public class UserJob {

    @XxlJob("testHandler")
    public ReturnT<String> testHandler(String param) throws Exception {
        log.info("立可得集成xxl-job");
        return ReturnT.SUCCESS;
    }


    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 每日工单量列表初始化
     *
     * @param param
     * @return
     * @throws Exception
     */
    @XxlJob("workCountInitJobHandler")
    public ReturnT<String> workCountInitJobHandler(String param) throws Exception {
        //查询用户列表
        List<UserEntity> userEntities = userService.list();

        //从xxl-接收到的参数用于,控制工单刷新
        int plusDays = "0".equals(param) ? 0 : 1;  //0代表生成今日数据，1代表生成次日数据，测试时参数输入0
        //构建数据（zset）
        userEntities.stream().forEach(user -> {
            //只考虑非管理员
            if (!user.getRoleCode().equals("0")) {
                //创建key
                String key = VMSystem.REGION_TASK_KEY_PREF
                        //创建时间是当天任务,还是预先处理的明天的任务
                        + LocalDate.now().plusDays(plusDays)
                        .format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                        //用户所属区域,+用户角色
                        + "." + user.getRegionId() + "." + user.getRoleCode();
                //redis存值
                redisTemplate.opsForZSet().add(key, user.getId(), 0);
                //设置过期时间
                redisTemplate.expire(key, Duration.ofDays(2));

            }

        });

        return ReturnT.SUCCESS;
    }


}